import Mock from 'mockjs'
import { useUserListStore } from '@/stores/user'
import { useRegisterInfoStore } from '@/stores/user'

const userList = useUserListStore()
const registerInfo = useRegisterInfoStore()

function generateCode() {
    return String(parseInt(100000 + Math.random() * 900000))
}

// 验证手机号
Mock.mock('/register/checkTel', 'post', (config) => {
    const req = JSON.parse(config.body)
    const data = {
        code: '200',
        message: '手机号已注册',
        data: { checked: false }
    }
    const list = userList.userList
    let flag = true
    if (list.length != 0) {
        for (let i = 0; i < list.length; i++) {
            if (list[i].tel == req.tel) {
                flag = false;
                break
            }
        }
    }
    if (flag) {
        data.message = '继续注册'
        data.data.checked = true
        registerInfo.setTel(req.tel)
    }
    return data
})

// 获取验证码
Mock.mock('/register/getCode', 'post', (config) => {
    // const req = JSON.parse(config.body)
    const data = {
        code: '10010',
        message: '请先输入手机号',
        data: {}
    }
    if (registerInfo.registerInfo.tel) {
        registerInfo.setCode(generateCode())
        registerInfo.setChecked(false)
        data.code = '200'
        data.message = '获取验证码成功'
        data.data = {
            code: registerInfo.registerInfo.code
        }
    }

    return data
})

// 验证验证码
Mock.mock('/register/checkedCode', 'post', (config) => {
    const req = JSON.parse(config.body)

    const data = {
        code: '200',
        message: '验证码错误',
        data: {
            flag: false
        }
    }

    if (registerInfo.registerInfo.code == req.code) {
        data.message = '继续注册'
        data.data.flag = true
        registerInfo.setChecked(true)
    }
    // console.log(registerInfo.registerInfo);

    return data
})

// 设置密码
Mock.mock('/register/setPassword', 'post', (config) => {
    const req = JSON.parse(config.body)
    const data = {
        code: '200',
        message: '注册失败',
        data: {}
    }
    if (registerInfo.registerInfo.checked) {
        const userInfo = {
            tel: registerInfo.registerInfo.tel,
            password: req.password,
            userid: 'user-' + String(Math.random()).slice(2),
            username: '用户' + String(Math.random()).slice(2,10),
            img: 'https://ss0.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3730063558,1625161022&fm=253&gp=0.jpg',
            likes: [],
            collects: [],
            historys: [],
            concern: [],
            post: [],
            fans: [],
            liked:[],
            comments:[],
        }
        userList.addUserList(userInfo)
        registerInfo.clear()
        data.message = '注册成功'
        data.data = {
            userInfo: userInfo,
        }
    }

    return data
})